package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.ChargeLogic;
import com.hotel.BL.ReservationLogic;
import com.hotel.BL.SubReservationLogic;

import data.Charge;
import data.Reservation;
import data.Room;
import data.SubReservation;
import data.passingData.ReservationDate;
import data.passingData.RoomtypeAndRoomTitle;


@SuppressWarnings("serial")
public class SubReservationService extends HttpServlet{
	//http://localhost:8080/subReservationService?func=SplitReservation&res=resId&from=date&to=date&roomtype=roomtype&room=room
	//http://localhost:8080/subReservationService?func=GetAllRoomInReservation&res=resId
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String func = req.getParameter("func");
			if(func.equals("SplitReservation")){
				SplitReservation(req,resp);
			}
			else if(func.equals("GetAllRoomInReservation")){
				GetAllRoomInReservation(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void SplitReservation(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{
		HttpSession session=req.getSession(true);	
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		long roomtypeId = Long.parseLong(req.getParameter("roomtype"));
		long roomId = Long.parseLong(req.getParameter("room"));
		long min = 0;
		if(req.getParameter("min") != null && req.getParameter("min") != "")
			min = Long.parseLong(req.getParameter("min"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
		
		Date from = (Date)formatter.parse(req.getParameter("from"));
		Date to = (Date)formatter.parse(req.getParameter("to"));
				
		SubReservationLogic subReservationLogic = new SubReservationLogic(req,resp);
		ReservationDate tmp = new ReservationDate();
		Reservation res = subReservationLogic.SplitReservation(hotelId, resId, roomtypeId, roomId, from, to);
		List<Charge> chargeList = new ArrayList<Charge>();
		if(res != null){
			String pbdString = new ReservationLogic(req,resp).EditPackageByDate(res.getPackageByDate(), res.getDate(), res.getDateTo());
			res.setPackageByDateString(pbdString);
			res = new ReservationLogic(req,resp).UpdateReservation(res);
			
			chargeList = new ChargeLogic(req,resp).CalCharge(hotelId, res.getSubReservationList(),
					res.getPackageByDate(), res.getDate(), res.getDateTo());

			tmp.setDate(res.getDate());
			tmp.setDateTo(res.getDateTo());
			tmp.setSpan(res.getSpan());
		}
			
		Gson gson = new Gson();
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("Result", res!=null);
		if(min==0)map.put("SubReservationList", res.getSubReservationList());
		if(min==0)map.put("PackageByDate", res.getPackageByDate());
		if(min==0)map.put("ReservationDate", tmp);
		if(min==0)map.put("ChargeList", chargeList);

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(map));
	}

	private void GetAllRoomInReservation(HttpServletRequest req, HttpServletResponse resp) throws IOException, ParseException
	{
		HttpSession session=req.getSession(true);	
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
		String df = req.getParameter("df");
		String dt = req.getParameter("dt");
		Date from = (df!=null)? (Date)formatter.parse(df) : new Date();
		Date to = (dt!=null)? (Date)formatter.parse(dt) : new Date();
		
		ReservationLogic rLogic = new ReservationLogic(req,resp);
		Reservation r = rLogic.GetReservation(resId);
		
		List<RoomtypeAndRoomTitle> obj = new ArrayList<RoomtypeAndRoomTitle>();
		SubReservation lastSub;
		
		if(r.getSubReservationList().size() == 0)
		{
			RoomtypeAndRoomTitle rs = new RoomtypeAndRoomTitle();
			rs.setRoomId(r.getRoom().getId());
			rs.setRoomName(r.getRoom().getRoomName());
			rs.setRoomTypeId(r.getRoomType().getId());
			rs.setRoomTypeShortName(r.getRoomType().getShortName());
			rs.setDateFrom(r.getDate());
			rs.setDateTo(r.getDateTo());
			rs.setResId(r.getId());
			obj.add(rs);
			
			lastSub = new SubReservation();
			lastSub.CloneReservation(r);
		}
		else
		{
			SubReservationLogic subLogic = new SubReservationLogic(req,resp);
			List<SubReservation> subList = subLogic.GetSubReservationFromResvId(hotelId,resId);
			boolean found = false;
			for(SubReservation s : subList)
			{
				found = false;
				for(RoomtypeAndRoomTitle rs : obj)
					if(rs.getRoomId() == s.getRoom().getId() && rs.getDateFrom().equals(s.getDate()))
						{ found = true; break; }
				if(!found)
				{
					RoomtypeAndRoomTitle rs = new RoomtypeAndRoomTitle();
					rs.setRoomId(s.getRoom().getId());
					rs.setRoomName(s.getRoom().getRoomName());
					rs.setRoomTypeId(s.getRoomType().getId());
					rs.setRoomTypeShortName(s.getRoomType().getShortName());
					rs.setDateFrom(s.getDate());
					rs.setDateTo(s.getDateTo());
					rs.setResId(s.getId());
					obj.add(rs);
				}
			}
			lastSub = subLogic.GetLastSubRes(subList);
		}
		
		ReservationDate resDate = new ReservationDate();
		resDate.setId(r.getId());
		resDate.setDate(r.getDate());
		resDate.setSpan(r.getSpan());
		resDate.setDateTo(r.getDateTo());
		
		HashMap<String,Object> hash = new HashMap<String,Object>();
		
		hash.put("ResDate", resDate);
		hash.put("Object", obj);
		
		if(df!=null && dt!=null){
			String roomIds = "";
			List<SubReservation> listUsedRoom = rLogic.GetUsedRoomWithinDate(hotelId,from,Util.daysBetween(from, to),lastSub.getRoomType().getId());
			List<Room> rooms = rLogic.GetBlankRoomWhichCanBeChangeRoomWithSellRoom(lastSub,listUsedRoom);
			for(Room rm:rooms){
				if(roomIds != "") roomIds += ",";
				roomIds += rm.getId();
			}
			hash.put("roomtype", lastSub.getRoomTypeString());
			hash.put("ExRoom", roomIds);
			hash.put("next", rLogic.GetNextAvaliableNextRoomWithSellRoom(lastSub,listUsedRoom).getId());
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(hash));
		
	}
}
